package C713;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * 使用管道发送消息
 *
 * @author admin
 * @version 1.0
 */
public class Test1 {
    public static void main(String[] args) throws IOException {
        //创建管道字节输入，输出流
        PipedInputStream pis = new PipedInputStream();
        PipedOutputStream pos = new PipedOutputStream(pis);
        Tree q = new Tree();
        Producer p = new Producer(q, pos);
        Consumer c = new Consumer(q, pis);
        p.start();
        c.start();
    }
}

//生产者
class Producer extends Thread {
    Tree q;
    PipedOutputStream pos;

    Producer(Tree q, PipedOutputStream pos) {
        this.q = q;
        this.pos = pos;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                while (!q.bFull) ;//不为空，才写入
                pos.write(i);
                System.out.println("Producer put " + i);
                q.bFull = !q.bFull;

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            //在全部发送完再关闭
            pos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//消费者
class Consumer extends Thread {
    Tree q;
    PipedInputStream pis;

    Consumer(Tree q, PipedInputStream pis) {
        this.q = q;
        this.pis = pis;
    }

    public void run() {

        for (int i = 0; i < 10; i++) {
            try {
                while (q.bFull) ;//为空，才读
                System.out.println("Consumer get " + pis.read());
                q.bFull = !q.bFull;
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        try {
            pis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/* 树类 **/
class Tree {
    //    private int hole;//不需要树洞，直接从管道中取
    boolean bFull = true;
}